package com.gj.config;

import com.gj.context.ApplicationContextHolder;
import com.gj.remote.HttpAgent;
import com.gj.remote.ServerHttpAgent;
import com.gj.support.DynamicThreadPoolConfigService;
import com.gj.support.DynamicThreadPoolPostProcessor;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(BootstrapProperties.class)
public class DynamicThreadPoolExecutorAutoConfiguration {

    //在这里把配置文件中的相关信息封封装到这个成员变量中了
    private final BootstrapProperties properties;

    //这里创建的这个hippo4JApplicationContextHolder对象其实就是对spring的Appliycation上下文对象做了一封包装
    //通过这个hippo4JApplicationContextHolder对象可以随时得到spring的Appliycation上下文对象了
    @Bean
    @ConditionalOnMissingBean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ApplicationContextHolder applicationContextHolder() {
        return new ApplicationContextHolder();
    }

    //远程通信组件，使用的是http通信方式
    @Bean
    public HttpAgent httpAgent(BootstrapProperties properties) {
        return new ServerHttpAgent(properties);
    }

    //BeanPostProcessor，springboot 项目启动的时候，注册动态线程池
    //动态线程池处理器，这个处理器其实是就是spring中的一个bean处理器，在这个bean处理器中把动态线程池包装成了DynamicThreadPoolRegisterWrapper对象
    //然后开始向服务端注册该动态线程池的信息
    @Bean
    public DynamicThreadPoolPostProcessor threadPoolBeanPostProcessor(HttpAgent httpAgent, DynamicThreadPoolConfigService dynamicThreadPoolConfigService) {
        return new DynamicThreadPoolPostProcessor(properties, httpAgent, dynamicThreadPoolConfigService);
    }

    //向服务端发送注册请求
    @Bean
    public DynamicThreadPoolConfigService dynamicThreadPoolConfigService(HttpAgent httpAgent) {
        return new DynamicThreadPoolConfigService(httpAgent);
    }
}
